import { createStore } from "vuex";
import { getUserInfo } from '@/config/api/user.js'

// Vuex.Store 构造器选项
const store = createStore({
	// 为了不和页面或组件的data中的造成混淆，state中的变量前面建议加上$符号
	state: {
		// 用户信息
		$userInfo: uni.getStorageSync("userInfo") || {},
		$token: uni.getStorageSync("token") || "",
		$activeCar: {},
		$userID: uni.getStorageSync("userID") || null,
	},
	mutations: {
		setToken(state, payload) {
			state.$token = payload.token
		},
		setUserInfo(state, payload) {
			// 变更状态
			state.$userInfo = payload
			uni.setStorage({
				key: "userInfo",
				data: payload
			})

		},
		setUserID(state, payload) {
			// 变更状态
			state.$userID = payload
			uni.setStorage({
				key: "userID",
				data: payload
			})

		},
		logout(state) {
			state.$userInfo = {};
			state.$token = "";
			state.$userID = null;
			uni.removeStorage({
				key: 'userInfo'
			});
			uni.removeStorage({
				key: 'token'
			})
			uni.removeStorage({
				key: 'userID'
			})
		},

		activeCar(state, payload) {
			state.$activeCar = payload
		}
	},
	actions: {
		async setToken(context, payload) {
			context.commit('setToken', payload)

			await uni.setStorage({
				key: "token",
				data: payload.token
			})

			const user = await getUserInfo()

			context.commit('setUserID', user.userId)
		},
		setUserInfoAction(context, payload) {
			context.commit('setUserInfo', payload)
		},
		logout(context, payload) {
			context.commit('logout')
		},
		setActiveCar(context, payload) {
			context.commit("activeCar", payload)
		}
	}
})

export default store